package com.smartscreen.baseinfomanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smartscreen.baseinfomanage.dto.CreateClassRequest;
import com.smartscreen.baseinfomanage.dto.StudentInfoDTO;
import com.smartscreen.baseinfomanage.dto.UpdateClassRequest;
import com.smartscreen.baseinfomanage.entity.Grade;
import com.smartscreen.baseinfomanage.entity.SchoolClass;
import com.smartscreen.baseinfomanage.entity.Student;
import com.smartscreen.baseinfomanage.entity.Teacher;
import com.smartscreen.baseinfomanage.mapper.GradeMapper;
import com.smartscreen.baseinfomanage.mapper.SchoolClassMapper;
import com.smartscreen.baseinfomanage.mapper.StudentMapper;
import com.smartscreen.baseinfomanage.mapper.TeacherMapper;
import com.smartscreen.baseinfomanage.service.GradeClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class GradeClassServiceImpl implements GradeClassService {

    @Autowired
    private GradeMapper gradeMapper;
    
    @Autowired
    private SchoolClassMapper schoolClassMapper;
    
    @Autowired
    private TeacherMapper teacherMapper;
    
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Grade> getAllGrades() {
        return gradeMapper.selectList(null);
    }

    @Override
    public List<SchoolClass> getClasses(String gradeId) {
        QueryWrapper<SchoolClass> queryWrapper = new QueryWrapper<>();
        if (gradeId != null && !gradeId.isEmpty()) {
            queryWrapper.eq("grade_id", gradeId);
        }
        List<SchoolClass> classes = schoolClassMapper.selectList(queryWrapper);
        
        // 填充班主任信息
        for (SchoolClass schoolClass : classes) {
            if (schoolClass.getHomeroomTeacherId() != null) {
                Teacher teacher = teacherMapper.selectById(schoolClass.getHomeroomTeacherId());
                schoolClass.setHomeroomTeacher(teacher);
            }
        }
        return classes;
    }

    @Override
    public SchoolClass createClass(CreateClassRequest request) {
        String newClassId = "c" + UUID.randomUUID().toString().substring(0, 8);
        
        SchoolClass newClass = new SchoolClass();
        newClass.setClassId(newClassId);
        newClass.setName(request.getName());
        newClass.setHomeroomTeacherId(request.getHomeroomTeacherId());
        
        schoolClassMapper.insert(newClass);
        
        // 填充班主任信息
        if (request.getHomeroomTeacherId() != null) {
            Teacher teacher = teacherMapper.selectById(request.getHomeroomTeacherId());
            newClass.setHomeroomTeacher(teacher);
        }
        
        return newClass;
    }

    @Override
    public SchoolClass getClassDetail(String classId) {
        SchoolClass schoolClass = schoolClassMapper.selectById(classId);
        if (schoolClass != null) {
            // 填充班主任信息
            if (schoolClass.getHomeroomTeacherId() != null) {
                Teacher teacher = teacherMapper.selectById(schoolClass.getHomeroomTeacherId());
                schoolClass.setHomeroomTeacher(teacher);
            }
            
            // 填充学生列表
            List<Student> students = studentMapper.selectByClassId(classId);
            schoolClass.setStudents(students);
        }
        return schoolClass;
    }

    @Override
    public void updateClass(String classId, UpdateClassRequest request) {
        SchoolClass schoolClass = schoolClassMapper.selectById(classId);
        if (schoolClass != null) {
            if (request.getName() != null) {
                schoolClass.setName(request.getName());
            }
            if (request.getHomeroomTeacherId() != null) {
                schoolClass.setHomeroomTeacherId(request.getHomeroomTeacherId());
            }
            schoolClassMapper.updateById(schoolClass);
        }
    }

    @Override
    public Map<String, Map<String, Object>> getClassesBatchAsMap(List<String> classIds) {
        if (classIds == null || classIds.isEmpty()) {
            return new HashMap<>();
        }

        // 去重并过滤空值
        List<String> validIds = classIds.stream()
                .filter(Objects::nonNull)
                .filter(id -> !id.trim().isEmpty())
                .distinct()
                .collect(Collectors.toList());

        if (validIds.isEmpty()) {
            return new HashMap<>();
        }

        // 批量查询班级信息
        List<SchoolClass> classes = schoolClassMapper.selectBatchIds(validIds);

        // 转换为Map格式
        Map<String, Map<String, Object>> result = new HashMap<>();
        for (SchoolClass schoolClass : classes) {
            Map<String, Object> classMap = new HashMap<>();
            classMap.put("classId", schoolClass.getClassId());
            classMap.put("name", schoolClass.getName());
            classMap.put("homeroomTeacherId", schoolClass.getHomeroomTeacherId());
            classMap.put("createdAt", schoolClass.getCreatedAt());
            classMap.put("updatedAt", schoolClass.getUpdatedAt());

            result.put(schoolClass.getClassId(), classMap);
        }

        return result;
    }

    @Override
    public Map<String, Map<String, Object>> getStudentsBatchAsMap(List<String> studentIds) {
        if (studentIds == null || studentIds.isEmpty()) {
            return new HashMap<>();
        }
    
        // 去重并过滤空值
        List<String> validIds = studentIds.stream()
                .filter(Objects::nonNull)
                .filter(id -> !id.trim().isEmpty())
                .distinct()
                .collect(Collectors.toList());
    
        if (validIds.isEmpty()) {
            return new HashMap<>();
        }
    
        // 批量查询学生信息
        List<Student> students = studentMapper.selectBatchIds(validIds);
    
        // 转换为Map格式
        Map<String, Map<String, Object>> result = new HashMap<>();
        for (Student student : students) {
            Map<String, Object> studentMap = new HashMap<>();
            studentMap.put("studentId", student.getStudentId());
            studentMap.put("name", student.getName());
            studentMap.put("studentNumber", student.getStudentNumber());
            studentMap.put("createdAt", student.getCreatedAt());
            studentMap.put("updatedAt", student.getUpdatedAt());
    
            result.put(student.getStudentId(), studentMap);
        }
    
        return result;
    }

    @Override
    public List<String> getStudentIdsByClassId(String classId) {
        List<Student> students = studentMapper.selectByClassId(classId);
        return students.stream()
                .map(Student::getStudentId)
                .collect(Collectors.toList());
    }

    @Override
    public List<StudentInfoDTO> getStudentsByNumbers(List<String> studentNumbers) {
        if (studentNumbers == null || studentNumbers.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 去重并过滤空值
        List<String> validNumbers = studentNumbers.stream()
                .filter(Objects::nonNull)
                .filter(number -> !number.trim().isEmpty())
                .distinct()
                .collect(Collectors.toList());
        
        if (validNumbers.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Student> students = studentMapper.selectByStudentNumbers(validNumbers);
        
        return students.stream()
                .map(this::convertToStudentInfoDTO)
                .collect(Collectors.toList());
    }

    /**
     * 将 Student 实体转换为 StudentInfoDTO
     */
    private StudentInfoDTO convertToStudentInfoDTO(Student student) {
        StudentInfoDTO dto = new StudentInfoDTO();
        dto.setStudentId(student.getStudentId());
        dto.setName(student.getName());
        dto.setStudentNumber(student.getStudentNumber());
        dto.setClassId(student.getClassId());
        dto.setCreatedAt(student.getCreatedAt());
        dto.setUpdatedAt(student.getUpdatedAt());
        return dto;
    }
}